using System;
using OpenFaq.AcceptanceTests.StepHelpers;
using TechTalk.SpecFlow;
using WatiN.Core;

namespace OpenFaq.AcceptanceTests.StepHelpers
{
    [Binding]
    public class ScenarioHelper
    {
        [BeforeScenario]
        public static void Open()
        {
            Action cleanup = () =>
                {
                    var link = WebBrowser.Current.Link(Find.ByText("Log Off"));

                    if (link.Exists)
                        link.Click();
                };

            ScenarioContext.Current.Add("CloseAction", cleanup);
        }
        
        [AfterScenario]
        public static void Close()
        {
            CallCloseAction();

            if (ScenarioContext.Current.ContainsKey("browser"))
                WebBrowser.Current.Close();
        }

        private static void CallCloseAction()
        {
            if (!ScenarioContext.Current.ContainsKey("CloseAction")) 
                return;
            
            var cleanup = ScenarioContext.Current["CloseAction"] as Action;

            if (cleanup != null)
                cleanup();
        }
    }
}